import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * @ClassName CollectionsDemo04
 * @Description TODO
 * @Author Li
 * @Date 2022/8/5 9:20
 * @ModifyDate 2022/8/5 9:20
 * @Version 1.0
 */
public class CollectionsDemo04 {
    public static void main(String[] args) {
        // 创建集合并添加数据
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("ZhangSan", 18));
        list.add(new Student("LiSi", 19));
        list.add(new Student("ZhangSa", 20));
        list.add(new Student("WangEr", 20));
        list.add(new Student("ZhangSang", 19));
        list.add(new Student("LiSi", 17));

        // 按指定规则排序：按姓名升序，姓名长度升序，年龄升序
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                String name1 = o1.getName();
                String name2 = o2.getName();
                int length1 = o1.getName().length();
                int length2 = o2.getName().length();
                // 3.姓名相同，按年龄升序
                if (o1.getName().equals(o2.getName())) {
                    return o1.getAge() - o2.getAge();
                } else {
                    int minLength = length1 < length2 ? length1 : length2;
                    for (int i = 0; i < minLength;i++){
                        if (name1.charAt(i) != name2.charAt(i)) {
                            // 1.按姓名升序
                            return name1.charAt(i) - name2.charAt(i);
                        }
                    }
                    // 2.按姓名长度升序
                    return length1 - length2;
                }
            }
        });
        for (Student student : list) {
            System.out.println(student);
        }
    }
}
